package com.ruoyi.web.controller.agent;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.ResponseResult;
import com.ruoyi.common.enums.OrderStatusEnum;
import com.ruoyi.common.utils.file.AliOss;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.OrderPay;
import com.ruoyi.system.dto.ApiChinaOrderPayAddDto;
import com.ruoyi.system.dto.NotifyOrderDto;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.OrderPayService;
import com.ruoyi.system.vo.SumAmountVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "商户后台:代付订单")
@RestController
@RequestMapping("agent/orderPay")
public class AgentOrderPayController extends BaseController {
    @Resource
    private OrderPayService baseService;

    @Resource
    private ISysConfigService configService  ;

    private String money="amount";

    @ApiOperation(value = "代付订单列表")
    @GetMapping("list")
    public ResponseResult<Map<String, Object>> list(OrderPay domain) {
        SysUser user = this.getLoginUser().getUser();
        OrderPay orderPay = new OrderPay();
        if (!StrUtil.equals(user.getRole(), "admin")) {
            domain.setMerchantId(user.getUserId());
            orderPay.setMerchantId(user.getUserId());
        }

        Map<String, Object> map = new HashMap<>();
        this.startPage();
        List<OrderPay> list = baseService.findList(domain);
        DateTime beginOfDay = DateUtil.beginOfDay(new Date());
        DateTime yestodayBegin = DateUtil.offsetDay(beginOfDay, -1);

        orderPay.setStatus(OrderStatusEnum.success.getValue());
        BigDecimal yestoday = baseService.sum("amount", orderPay, yestodayBegin, beginOfDay);
        BigDecimal today = baseService.sum("amount", orderPay, beginOfDay, new Date());
        BigDecimal totalAmount = baseService.sum("amount", orderPay, null, null);

        DateTime thisMonth = DateUtil.beginOfMonth(new Date());
        DateTime dateTime = DateUtil.offsetMonth(thisMonth, -1);
        BigDecimal thisMonthAmount = baseService.sum("amount", orderPay, thisMonth, new Date());
        BigDecimal preMonthAmount = baseService.sum("amount`", orderPay, dateTime, thisMonth);
        SumAmountVo sumAmountVo = new SumAmountVo();
        sumAmountVo.setTodayAmount(today);
        sumAmountVo.setYestodayAmount(yestoday);
        sumAmountVo.setTotalAmount(totalAmount);
        sumAmountVo.setPreMonthAmount(preMonthAmount);
        sumAmountVo.setThisMonthAmount(thisMonthAmount);
        map.put("sumAmountVo", sumAmountVo);
        map.put("pageResult", this.getPageResult(list));
        return this.setSuccessResult(map);
    }

    @ApiOperation(value = "代付下单")
    @PostMapping("createOrder")
    public ResponseResult createOrder(@RequestBody ApiChinaOrderPayAddDto apiChinaOrderPayAddDto) {
        SysUser user = this.getLoginUser().getUser();
        apiChinaOrderPayAddDto.setMerchantId(user.getUserId());
        apiChinaOrderPayAddDto.setMerchantOrderNo(UUID.randomUUID().toString());
        apiChinaOrderPayAddDto.setNotifyUrl(configService.selectConfigByKey("zfbNotifyUtl") + "/api/orderPay/notifyMe");

        this.baseService.createApiOrder(apiChinaOrderPayAddDto, "sys");
        return this.setSuccessResult();
    }

    @ApiOperation(value = "回调下游订单", notes = "传入商户订单号")
    @PostMapping("notifyAgent")
    public ResponseResult notifyAgent(@Valid @RequestBody NotifyOrderDto notifyOrderDto) {
        checkAdmin();
        OrderPay domain = this.baseService.check(notifyOrderDto.getId());
        if (!StrUtil.equals(domain.getStatus(), OrderStatusEnum.handling.getValue())) {
            return this.setErrorResult("状态不对,请刷新后重试");
        }
        domain.setStatus(notifyOrderDto.getMerchantOrderStatus());
        this.baseService.notifyAgent(domain);
        return this.setSuccessResult();
    }


    @ApiOperation(value = "已转账", notes = "传入商户订单号")
    @RequestMapping("hasPaid")
    public ResponseResult hasPaid(Long id) {
        checkAdmin();
        NotifyOrderDto notifyOrderDto = new NotifyOrderDto();
        notifyOrderDto.setId(id);
        notifyOrderDto.setMerchantOrderStatus(OrderStatusEnum.success.getValue());
        OrderPay domain = this.baseService.check(notifyOrderDto.getId());
        if (!StrUtil.equals(domain.getStatus(), OrderStatusEnum.handling.getValue())) {
            return this.setErrorResult("状态不对,请刷新后重试");
        }
//        if (StrUtil.isBlank(domain.getPic())) {
//            return this.setErrorResult("请先上传凭证");
//        }
        domain.setStatus(notifyOrderDto.getMerchantOrderStatus());
        this.baseService.notifyAgent(domain);
        return this.setSuccessResult();
    }

    @ApiOperation(value = "回调下游订单", notes = "传入商户订单号")
    @RequestMapping("reject")
    public ResponseResult reject(Long id) {
        checkAdmin();
        NotifyOrderDto notifyOrderDto = new NotifyOrderDto();
        notifyOrderDto.setId(id);
        notifyOrderDto.setMerchantOrderStatus(OrderStatusEnum.reject.getValue());
        return notifyAgent(notifyOrderDto);
    }


    @ApiOperation(value = "补发通知", notes = "传入商户订单号")
    @RequestMapping("notice")
    public ResponseResult notice(Long id) {
        OrderPay domain = this.baseService.getById(id);
        if (StrUtil.equals(domain.getStatus(), OrderStatusEnum.handling.getValue())) {
            return this.setErrorResult("请先处理订单后再补发");
        }
        domain.setRemark(domain.getRemark());
        this.baseService.notice(domain);
        return this.setSuccessResult();
    }


    @ApiOperation(value = "上传图片", notes = "传入商户订单号")
    @PostMapping("/uploadPic")
    public ResponseResult uploadPic(@RequestParam("avatarfile") MultipartFile file, @RequestParam("id") String id) throws Exception {
        checkAdmin();
//        String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
//        String pic = RuoYiConfig.getFileApi() + avatar;
        String filename = FileUploadUtils.extractFilename(file);
        String pic = AliOss.uploadToOss(file, "umashang/orderPay/"+filename);
        OrderPay orderPay = this.baseService.check(Long.valueOf(id));
        orderPay.setPic(pic);
        this.baseService.updateDomain(orderPay);
        return ResponseResult.createBySuccess();
    }

    @ApiOperation(value = "上传图片111", notes = "传入商户订单号")
    @PostMapping("/public/uploadToOss")
    public ResponseResult uploadToOss(@RequestParam("avatarfile") MultipartFile file, @RequestParam("id") String id) throws Exception {

        String filename = FileUploadUtils.extractFilename(file);
        String pic = AliOss.uploadToOss(file, "umashang/orderPay/"+filename);

        return ResponseResult.createBySuccess(pic);
    }


}
